const app = getApp();
import {
  post
} from '../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fixedHeader: false,
    globalData: app.globalData,

    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 3000,
    duration: 500,

    info: null,
    config: null,
  },

  toSearch() {
    wx.navigateTo({
      url: '/pages/search/index',
    });
  },

  // 页面跳转
  toPage(e) {
    let {
      url,
      info
    } = e.currentTarget.dataset;
    if (url) {
      if (url === 'previewImage') {
        wx.previewImage({
          urls: info.cmsPageItems.map(d => d.img),
        });
        return;
      }
      if (url.startsWith("tab")) {
        wx.switchTab({
          url: url.replace('tab', ''),
        });
        return;
      }
      wx.navigateTo({
        url: url,
      });
    }
  },

  getList() {
    post(`/cms/page-info/home/${app.globalData.tenantCode}`)
      .then(resp => {
        if (resp.code === 0) {
          this.setData({
            info: resp.data.map(d => {
              d.cmsPageItems = d.cmsPageItems.map(data => {
                if (data.mallGoods) {
                  data.mallGoods.album = JSON.parse(data.mallGoods.album);
                }
                if (data.mallServe) {
                  data.mallServe.album = JSON.parse(data.mallServe.album);
                }
                return data;
              })
              return d;
            })
          });
        }
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setBackgroundColor({
      backgroundColor: "#f6f6f6"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.getConfig(config => {
      this.setData({config});
    });

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }

    this.getList();
  },

  /**
   * 页面滚动监听
   */
  onPageScroll(e) {
    if (this.data.fixedHeader) {
      if (e.scrollTop < (this.data.globalData.statusBarHeight + this.data.globalData.titleHeight)) {
        this.setData({
          fixedHeader: false,
        });
      }
    } else {
      if (e.scrollTop > (this.data.globalData.statusBarHeight + this.data.globalData.titleHeight)) {
        this.setData({
          fixedHeader: true,
        });
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.config.name,
    }
  },

});